<!-- 派件作业管理 -->
<template>
  <div class="dashboard-container pickup-task customer-list-box">
    <div class="app-container">
      <el-card class="search-card-box" shadow="never">
        <el-form ref="operationalSearchFormData" :model="operationalSearchFormData" class="demo-form-inline" label-width="80px">
          <el-row :gutter="60">
            <el-col :span="8">
              <el-form-item label="取件任务编号:" style="margin-bottom: 0px" label-width="110px">
                <el-input v-model="operationalSearchFormData.id" placeholder="请输入取件任务编号" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单编号:" style="margin-bottom: 0px" label-width="110px">
                <el-input v-model="operationalSearchFormData.orderNumber" placeholder="请输入订单编号" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属营业部:" style="margin-bottom: 20px" label-width="110px">
                <treeselect v-model="operationalSearchFormData.departmentId" :options="agencyOptions" :normalizer="normalizer"
                  :searchable="true" style="width: 100%" placeholder="请选择所属营业部" no-options-text="暂无数据" no-results-text="暂无数据"
                  @select="selectAgency" @open="open" @close="close"/>
                <img ref="arrow" src="../../../assets/pullDown.png"
                  style=" position: absolute; width: 18px; height: 18px; right: 9px;
                    top: 12px; cursor: pointer; pointer-events: none; transition-duration: 0.3s;"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="签收状态:" style="margin-bottom: 15px" label-width="110px">
                  <el-select v-model="operationalSearchFormData.signStatus" clearable placeholder="请选择">
                    <el-option v-for="item in signStatusList" :key="item.value" :label="item.key" :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
            <el-col :span="8">
              <el-form-item label="预计完成时间:" style="margin-bottom: 20px" label-width="110px">
                <el-date-picker v-model="estimatedTime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" 
                  type="datetimerange" placeholder="选择预计完成时间" range-separator="至"
                  start-placeholder="开始时间" end-placeholder="结束时间" @change="handleEstimatedTimeChange()">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际完成时间:" style="margin-bottom: 20px" label-width="110px">
                <el-date-picker v-model="actualTime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetimerange" placeholder="选择预计完成时间" range-separator="至"
                  start-placeholder="开始时间" end-placeholder="结束时间" @change="handleActualTimeChange()">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="任务分配状态:" style="margin-bottom: 20px" label-width="110px">
                <el-select v-model="operationalSearchFormData.assignStatus" clearable placeholder="请选择任务分配状态">
                  <el-option v-for="item in operationOptions" :key="item.value" :label="item.key" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-button type="warning" @click="handleFilter('查询')">搜索</el-button>
              <el-button plain class="reset-btn" @click="resetForm('operationalSearchFormData')">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <TabChange :default-active-index="0" :is-show-num="false" :setting-list="mailStatusList" @tabChange="tabChange"/>
      <div v-loading="listLoading" :class="{ 'loading-box': listLoading }" element-loading-text="加载中" style="margin-top: 20px">
        <el-card class="table-card-box" shadow="never">
          <el-button class="customer-add-btn" @click="handleAddCourier(multipleSelection)">人工分配</el-button>
          <el-table :key="tableKey" ref="multipleTable" :data="dataList" fit style="width: 100%"
            stripe :header-cell-style="{ background: 'rgba(250,252,255,1)' }" :header-cell-class-name="isTableDisabled ? 'disabled' : 'able'"
            @selection-change="handleSelectionChange">
            <div v-show="(!dataList || dataList.length <= 0) && !listLoading && !searchkey" slot="empty">
              <img src="@/icons/pic-kong@2x.png" alt="img" style="margin-top: 20px; width: 25%; height: 25%"/>
              <p style="margin-top: -20px; padding-bottom: 0px">这里空空如也</p>
            </div>
            <el-card v-show="(!dataList || dataList.length <= 0) && !listLoading && searchkey" slot="empty" class="table-empty-box" shadow="never">
              <empty></empty>
            </el-card>
            <el-table-column align="center" type="selection" width="40" fixed :selectable="selectEnable"/>
            <el-table-column align="center" type="index" label="序号" width="60">
              <template slot-scope="scope">
                <span>{{ scope.$index +(operationalSearchFormData.pageNum - 1) * operationalSearchFormData.pageSize + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="取件作业编号" min-width="160" prop="id"/>
            <el-table-column align="center" label="所在营业部" min-width="160" prop="departmentName"/>
            <el-table-column align="center" label="任务分配状态" min-width="120">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.assignStatus === 1" size="small" type="danger">未分配</el-tag>
                <el-tag v-if="scope.row.assignStatus === 2" size="small" type="success">已分配</el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" label="快递员姓名" min-width="160" prop="courierName"/>
            <el-table-column align="center" label="订单编号" min-width="160" prop="orderNumber"/>
            <el-table-column v-if="operationalSearchFormData.mailStatus === 2" align="center" label="签收类型" min-width="160" prop="cancelTime">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.signRecipient === 1" size="small" type="success">本人</el-tag>
                <el-tag v-if="scope.row.signRecipient === 2" size="small" type="danger">代收</el-tag>
              </template>              
            </el-table-column>
            <el-table-column v-if="operationalSearchFormData.mailStatus === 3" align="center" label="取消时间" min-width="160" prop="cancelTime" />
            <el-table-column v-if="operationalSearchFormData.mailStatus === 3" align="center" label="取消原因" min-width="160" prop="cancelReason"/>
            <el-table-column v-if="[1,2].includes(operationalSearchFormData.mailStatus)" align="center" label="预计开始时间" min-width="160" prop="estimatedStartTime"/>
            <el-table-column v-if="[1,2].includes(operationalSearchFormData.mailStatus)" align="center" label="预计完成时间" min-width="160" prop="estimatedEndTime"/>
            <el-table-column v-if="operationalSearchFormData.mailStatus === 2" key="actualEndTime" align="center" label="实际完成时间" min-width="160" prop="actualEndTime"/>
          </el-table>
          <!-- end -->
          <!-- 分页 -->
          <div class="pagination">
            <div v-show="dataList && dataList.length > 0" class="pages">
              <el-pagination
              :total="Number(operationalSearchFormData.total)"
                :current-page="Number(operationalSearchFormData.pageNum)"
                :page-size="Number(operationalSearchFormData.pageSize)"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
          <!-- end -->
          <el-dialog class="add-form-dialog" :title="titleInfo.text" :visible.sync="dialogFormVisible" width="600px">
            <el-form ref="dataForm" label-position="right">
              <el-form-item label="选择快递员：" prop="courierName" :label-width="formLabelWidth">
                <el-select v-model="courierId" value-key="item.userId" placeholder="请选择" clearable filterable @change="handleChange">
                  <el-option v-for="item in courierOptions" :key="item.userId" :label="item.name" :value="item.userId"/>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center">
              <el-button class="save-btn" @click="createData">确定</el-button>
              <el-button class="cancel-btn" @click="cancelFn">取消</el-button>
            </div>
          </el-dialog>
        </el-card>
      </div>
    </div>
  </div>
</template>
<script>
import {pickupTaskList, courierList, dispatchTaskForCourier} from '@/api/branch'
import { getNotNullParams } from '@/utils/index'
import Treeselect from '@riophae/vue-treeselect'
import TabChange from '@/components/TabChange'
import { agencyList } from '@/api/institutions'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { enumsList } from '@/api/common'
export default {
  components: {
    Treeselect,
    TabChange
  },
  props: {
    getNewDisabled: Boolean
  },
  data() {
    return {      
      isTableDisabled: false,    // 表头全选是否禁用
      mailStatusList: [],        // 快递状态集合
      operationOptions: [],      // 分配状态集合
      signStatusList: [],        // 签收状态集合
      signRecipientList: [],     // 签收类型集合
      courierId: '',             // 快递员id
      formLabelWidth: '100px',
      multipleSelection: [],     //人工分配
      tableKey: 0,
      dataList: [],              //快递任务集合
      searchkey: false,
      courierOptions: {},
      listLoading: true,
      dialogFormVisible: false,
      operationalSearchFormData: {
        pageNum: 1,         //页码
        pageSize: 10,       //每页数量
        total: 0,           //总数量
        taskType: 2,        //派件
        id: '',             //快递系统编号
        departmentId: null, //机构系统编号
        courierId: '',      //快递员系统编号
        orderNumber: '',    //订单编号
        assignStatus: '',   //分配状态
        signStatus: '',     //签收状态
        signRecipient: '',  //签收类型
        mailStatus: '',     //业务状态
        estimatedStartTime: '',
        estimatedEndTime: '',
        actualStartTime: '',
        actualEndTime: ''
      },
      actualTime: [],       //实际完成时间数组
      estimatedTime: [],    //预计完成时间数组
      courierParams: {
        page: 1,
        pageSize: 1000,
        agentId: ''
      },
      titleInfo: {
        pageTitle: '',
        text: ''
      },
      selectedAgencyList: [],
      agencyOptions: [],     //机构
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }        
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      }
    }
  },
  computed: {
    status() {
      return status
    }
  },
  // 挂载结束
  mounted: function () {},
  // 创建完毕状态
  created() {
    this.getEnumList()
    this.getAgencyList()
    this.initialDate()
  },
  // 组件更新
  updated: function () {},
  methods: {
    selectEnable(row) {
      if (row.assignedStatus === 2) {
        return false
      } else {
        return true
      }
    },
    tabChange(val) {
      this.operationalSearchFormData.mailStatus = val
      this.getList()
    },
    //营业机构选择
    selectAgency(val) {
      this.operationalSearchFormData.departmentId = val.id
    },
    //实际完成时间处理
    handleActualTimeChange(val) {
      if (val) {
        this.operationalSearchFormData.actualStartTime = val[0]
        this.operationalSearchFormData.actualEndTime = val[1]
      } else {
        this.operationalSearchFormData.actualStartTime = ''
        this.operationalSearchFormData.actualEndTime = ''       
      }
    },
    //预计完成时间处理
    handleEstimatedTimeChange(val) {
      if (val) {
        this.operationalSearchFormData.estimatedStartTime = val[0]
        this.operationalSearchFormData.estimatedEndTime = val[1]
      } else {
        this.operationalSearchFormData.estimatedStartTime = ''
        this.operationalSearchFormData.estimatedEndTime = ''       
      }
    },
    open() {
      this.$refs.arrow.style.transform = 'rotate(-180deg)'
    },
    close() {
      this.$refs.arrow.style.transform = 'rotate(0deg)'
    },
    // 获取起始/目的地机构列表数据
    async getAgencyList() {
      const { data: res } = await agencyList()
      // 获取数据给options
      this.agencyOptions = res
    },
    // 快递员下拉选择
    handleChange(val) {
      this.courierId = val
    },
    // 取消弹框
    cancelFn() {
      this.dialogFormVisible = false
      this.$refs['dataForm'].resetFields()
    },
    // 初始数据
    initialDate() {
      // 读取数据
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.id)
      this.selectedAgencyList = Array.from(
        new Set(val.map((item) => item.agencyId))
      )
      if (!this.courierParams.agentId) {
        this.getLineList()
      }
      this.courierParams.agentId = this.selectedAgencyList[0]
    },
    // 获取快递员列表数据
    async getLineList() {
      const { data: res } = await courierList(this.courierParams)
      // 获取数据给options
      this.courierOptions = res.items
    },
    // 获取取件任务列表数据
    async getList() {
      this.listLoading = true
      if (this.operationalSearchFormData.mailStatus === 0) {
        this.operationalSearchFormData.mailStatus = ''
      }
      const { data: res } = await pickupTaskList(this.operationalSearchFormData)
      this.listLoading = false
      // 获取数据给dataList
      this.dataList = res.records
      this.operationalSearchFormData.total = res.total
      // 当页全禁用时表头多选也禁用
      this.isTableDisabled = this.dataList.every(
        (item) => item.assignedStatus === 2
      )
      // 获取总条数
      this.total = res.counts
    },
    // 搜索信息
    handleFilter() {
      this.getList(this.operationalSearchFormData)
      this.searchkey = true
    },
    // 重置
    resetForm(operationalSearchFormData) {
      this.$refs[operationalSearchFormData].resetFields()
      this.operationalSearchFormData.page = 1
      this.operationalSearchFormData.pageSize = 10
      this.operationalSearchFormData.taskType = 1
      this.operationalSearchFormData.id = ''
      this.operationalSearchFormData.orderId = ''
      this.operationalSearchFormData.agencyId = ''
      this.operationalSearchFormData.minEstimatedEndTime = ''
      this.searchkey = false
      this.operationalSearchFormData.maxEstimatedEndTime = ''
      this.operationalSearchFormData.minActualEndTime = ''
      this.operationalSearchFormData.maxActualEndTime = ''
      this.operationalSearchFormData.assignedStatus = ''
      this.actualTime = []
      this.estimatedTime = []
      this.getList()
    },
    // 每页显示信息条数
    handleSizeChange(val) {
      this.operationalSearchFormData.pageSize = val
      if (this.operationalSearchFormData.page === 1) {
        this.getList(this.operationalSearchFormData)
      }
    },
    // 进入某一页
    handleCurrentChange(val) {
      this.operationalSearchFormData.page = val
      this.getList()
    },
    // 分配快递员
    handleAddCourier() {
      const length = this.multipleSelection.length
      if (length === 0) {
        this.$message({
          message: '选择要分配的作业！',
          type: 'error'
        })
        return
      }
      if (this.selectedAgencyList.length > 1) {
        this.$message({
          message: '请选择一个营业部下面的取件作业！',
          type: 'error'
        })
        return
      }
      this.dialogFormVisible = true
      this.titleInfo.text = '人工分配'
    },
    // 弹层隐藏
    dialogFormH() {
      this.dialogFormVisible = false
    },
    // 表单提交
    async createData() {
      if (!this.courierId) {
        return this.$message.error('请选择快递员')
      }
      this.dialogFormH()
      await dispatchTaskForCourier({
        ids: this.multipleSelection,
        courierId: this.courierId
      })
        .then((res) => {
          if (String(res.code) === '200') {
            this.$message.success('人工分配成功')
            this.getList(this.operationalSearchFormData)
            this.courierId = ''
            this.multipleSelection = []
            this.selectedAgencyList = []
          }
          this.$refs.multipleTable.clearSelection()
        })
        .catch((err) => {
          this.courierId = ''
          this.multipleSelection = []
          this.selectedAgencyList = []
          this.$refs.multipleTable.clearSelection()
          this.$message.error(err.msg || '人工分配失败')
        })
    },
    // 查看运单详情
    handleWayllDetail(id) {
      // eslint-disable-next-line object-curly-spacing
      this.$router.push({ path: '/business/waybill-detail', query: { id: id } })
    },

    // 枚举获取
    async getEnumList(){
      const { data: enums } = await enumsList()
      this.mailStatusList = enums.MailStatusEnum
      this.signStatusList = enums.SignStatusEnum
      this.operationOptions = enums.AssignStatusEnum
      this.signRecipientList = enums.SignRecipientEnum
    }
  }
}
</script>
<style lang="scss" scoped>
.pagination {
  margin-top: 40px;
}
.dashboard-container {
  width: 100%;
}
.el-card {
  border-radius: 0;
  border: none;
  .el-card__header {
    background: #f8faff;
    /* padding: 10px 20px !important; */
    border-bottom: 0px solid #e6ebf5;
  }
}

// 下拉框
::v-deep .el-select {
  width: 100%;
}
</style>

<style lang="scss" scoped>
::v-deep .el-card {
  overflow: initial;
}
::v-deep .vue-treeselect__menu-container {
  z-index: 9999 !important;
}
</style>
